﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WxSDK.BLL
{
    public class Base<T>
    {
        WxCarroit.WxSdkEvan database;

        public Base()
        {
            database = new WxCarroit.WxSdkEvan();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="connectionStringName">连接字符串</param>
        public Base(string connectionStringName)
        {
            database = new WxCarroit.WxSdkEvan(connectionStringName);
        }


        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public virtual bool Exists(object Id)
        {
            return database.Exists<T>(Id);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="where"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public virtual bool Exists(string where, params object[] param)
        {
            return database.Exists<T>(where, param);
        }
        public int UpdateField(object PrimaryKey, string setsql, params object[] args)
        {
            return database.UpdateField<T>(PrimaryKey, setsql, args);
        }

        public int UpdateField(string wheresql, string setsql, params object[] args)
        {
            return database.UpdateField<T>(wheresql, setsql, args);
        }


        public object UpdateField(int id, string field, int value)
        {
            
            

            if (id > 0 && !string.IsNullOrEmpty(field))
            {
                field = field.ToLower();
                int res = UpdateField(id, field + "=" + value);

                return res;
            }
            
            return null;
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public virtual int Add(T model)
        {
            try
            {
                int res = int.Parse(database.Add(model).ToString());
                return res;
            }

            catch
            {
                return 0;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public virtual T GetModel(int Id)
        {
            return database.GetModel<T>(Id);
        }

        public virtual T GetModel(int Id, string ver)
        {
            return database.GetModel<T>("where islock>-1 and id=@0 and ver=@1 ", Id, ver);
        }

        public virtual T GetModel(string where, params object[] param)
        {
            return database.GetModel<T>(where, param);
        }

        public virtual int Delete(string Where, params object[] param)
        {
            return database.Delete<T>(Where, param);
        }

 
        public virtual int Delete(int id, params object[] param)
        {
            return database.Delete<T>(" islock>-1 and id=" + id, param);
        }

        public virtual IEnumerable<T> Query(string Where, params object[] param)
        {
            return database.Query<T>(Where, param);
        }

        public virtual IEnumerable<T> Query(int top, string Where, params object[] param)
        {
            var pd = WxPetaPoco.Database.PocoData.ForType(typeof(T));

            return database.Query<T>(string.Format("select {3} * from {0}{1} where {2} ", database.EscapeTableName(pd.TableInfo.TableName), Where, top > 0 ? " top " + top : string.Empty), param);
        }

        public virtual IEnumerable<T> Query(int top, string Where, string Order, params object[] param)
        {
            var pd = WxPetaPoco.Database.PocoData.ForType(typeof(T));
            return database.Query<T>(string.Format("select {2} * from {0} where {1} order by {3}",
                database.EscapeTableName(pd.TableInfo.TableName),
                Where,
                top > 0 ? " top " + top : string.Empty,
                Order), param);
        }

        public virtual WxPetaPoco.Page<T> Page(long pageSize, long currentPage, string strWhere, string filedOrder, params object[] param)
        {
            return database.Page<T>(pageSize, currentPage, strWhere, filedOrder, param);
        }

        ///// <summary>
        ///// 增加一条数据(2015.9.15 注册添加)
        ///// </summary>
        //[Mines.Ajax.AjaxMethod]
        //public virtual int Add(T model)
        //{
        //    try
        //    {
        //        int res = int.Parse(database.Add(model).ToString());
        //        return res;
        //    }
        //    catch
        //    {
        //        return 0;
        //    }
        //}


        ///// <summary>
        ///// 更新一条数据(2015.9.17)
        ///// </summary>
        //[Mines.Ajax.AjaxMethod]
        //public virtual object Update2(T model)
        //{
        //    return database.Update(model);
        //}
        ///// <summary>
        ///// 是否存在该记录
        ///// </summary>
        //[Mines.Ajax.AjaxMethod]
        //public virtual bool Exists(object Id)
        //{
        //    return database.Exists<T>(Id);
        //}

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="where"></param>
        ///// <param name="param"></param>
        ///// <returns></returns>
        //[Mines.Ajax.AjaxMethod]
        //public virtual bool Exists(string where, params object[] param)
        //{
        //    return database.Exists<T>(where, param);
        //}
        ///// <summary>
        ///// 得到一个对象实体
        ///// </summary>
        //[Mines.Ajax.AjaxMethod]
        //public virtual T GetModel(int Id)
        //{
        //    return database.GetModel<T>(Id);
        //}
        //[Mines.Ajax.AjaxMethod]
        //public virtual T GetModel(string where, params object[] param)
        //{
        //    return database.GetModel<T>(where, param);
        //}
        //[Mines.Ajax.AjaxMethod]
        //public virtual int Delete(string Where, params object[] param)
        //{
        //    return database.Delete<T>(Where, param);
        //}
        //[Mines.Ajax.AjaxMethod]
        //public virtual int Delete(int id, params object[] param)
        //{
        //    return database.Delete<T>(" id=" + id, param);
        //}
        //[Mines.Ajax.AjaxMethod]
        //public virtual IEnumerable<T> Query(string Where, params object[] param)
        //{
        //    return database.Query<T>(Where, param);
        //}
        //[Mines.Ajax.AjaxMethod]
        //public virtual IEnumerable<T> Query(int top, string Where, params object[] param)
        //{
        //    var pd = PetaPoco.Database.PocoData.ForType(typeof(T));

        //    return database.Query<T>(string.Format("select {2} * from {0} where {1} ", database.EscapeTableName(pd.TableInfo.TableName), Where, top > 0 ? " top " + top : string.Empty), param);
        //}
        //[Mines.Ajax.AjaxMethod]
        //public virtual IEnumerable<T> Query(int top, string Where, string Order, params object[] param)
        //{
        //    var pd = PetaPoco.Database.PocoData.ForType(typeof(T));
        //    return database.Query<T>(string.Format("select {2} * from {0} where {1}  order by {3}",
        //        database.EscapeTableName(pd.TableInfo.TableName),
        //        Where,
        //        top > 0 ? " top " + top : string.Empty,
        //        Order), param);
        //}
        //[Mines.Ajax.AjaxMethod]
        //public virtual PetaPoco.Page<T> Page(long pageSize, long currentPage, string strWhere, string filedOrder, params object[] param)
        //{
        //    return database.Page<T>(pageSize, currentPage, strWhere, filedOrder, param);
        //}


#if false

        //public int AddSystemLog(Model.SystemLog model)
        //{
        //    return new BLL.SystemLog().Add(model);
        //}
        #region CreateHtml
        //[Mines.Ajax.AjaxMethod]
        //public virtual bool CacheModel(T model)
        //{
        //    if (model == null)
        //        return false;
        //    Common.Utils.WriteSession("cachemodel", model);
        //    return true;
        //}

        /// <summary>
        /// 生成此栏目所有页面
        /// </summary>
        /// <param name="classid"></param>
        /// <returns></returns>
        //[Mines.Ajax.AjaxMethod]
        //public virtual int CreateAllHtml(int classid, string ver)
        //{
        //    Model.Administrator admin;
        //    if (!Administrator.IsAdminLogin(out admin))
        //    {
        //        throw new AdministratorException("非法操作：未登录");
        //    }

        //    Smarta.Model.Channel channel = new BLL.Channel().GetModel(classid, ver);

        //    if (channel != null)
        //    {
        //        if (!string.IsNullOrEmpty(channel.WebIndex))
        //            CreateHtmlPage.CreateHtmlYDPage(channel, ver);
        //        if (typeof(T).Name == "Downloads")
        //            CreateHtmlPage.CreateHtmlListAndDetailPage<T>(channel, ver, false);
        //        else
        //            CreateHtmlPage.CreateHtmlListAndDetailPage<T>(channel, ver, true);
        //        AddSystemLog(new Model.SystemLog
        //        {
        //            AddTime = DateTime.Now,
        //            Content = "成功生成 " + channel.SubTitle + "栏目所有页面",
        //            Title = "成功生成 " + channel.SubTitle + "栏目所有页面",
        //            UserId = admin.Id,
        //            UserName = admin.UserName
        //        });

        //        return 1;
        //    }
        //    AddSystemLog(new Model.SystemLog
        //    {
        //        AddTime = DateTime.Now,
        //        Content = "生成 “" + channel.SubTitle + "”栏目所有页面失败",
        //        Title = "生成 “" + channel.SubTitle + "”栏目所有页面失败",
        //        UserId = admin.Id,
        //        UserName = admin.UserName
        //    });

        //    return 0;
        //}

        /// <summary>
        /// 生成此栏目列表页
        /// </summary>
        /// <param name="classid"></param>
        /// <returns></returns>
        //[Mines.Ajax.AjaxMethod]
        //public virtual int CreateListHtml(int classid, string ver)
        //{
        //    Model.Administrator admin;
        //    if (!Administrator.IsAdminLogin(out admin))
        //    {
        //        throw new AdministratorException("非法操作，未登录");
        //    }

        //    Smarta.Model.Channel channel = new BLL.Channel().GetModel(classid, ver);

        //    if (channel != null)
        //    {
        //        CreateHtmlPage.CreateHtmlListAndDetailPage<T>(channel, ver, false);
        //        AddSystemLog(new Model.SystemLog
        //        {
        //            AddTime = DateTime.Now,
        //            Content = "成功生成“" + channel.SubTitle + "”栏目列表页面成功",
        //            Title = "成功生成“" + channel.SubTitle + "”栏目列表页面成功",
        //            UserId = admin.Id,
        //            UserName = admin.UserName
        //        });
        //        return 1;
        //    }
        //    AddSystemLog(new Model.SystemLog
        //    {
        //        AddTime = DateTime.Now,
        //        Content = "生成“" + channel.SubTitle + "”栏目列表页面失败",
        //        Title = "生成“" + channel.SubTitle + "”栏目列表页面失败",
        //        UserId = admin.Id,
        //        UserName = admin.UserName
        //    });
        //    return 0;
        //}

        /// <summary>
        /// 生成此栏目详细页
        /// </summary>
        /// <param name="classid"></param>
        /// <returns></returns>
        //[Mines.Ajax.AjaxMethod]
        //public virtual int CreateDetailHtml(int classid, string ver)
        //{
        //    Model.Administrator admin;
        //    if (!Administrator.IsAdminLogin(out admin))
        //    {
        //        throw new AdministratorException("非法操作，未登录");
        //    }

        //    Smarta.Model.Channel channel = new BLL.Channel().GetModel(classid, ver);

        //    if (channel != null)
        //    {
        //        CreateHtmlPage.CreateHtmlDetailPage<T>(channel, ver);
        //        AddSystemLog(new Model.SystemLog
        //        {
        //            AddTime = DateTime.Now,
        //            Content = "成功生成 “" + channel.SubTitle + "”栏目详细页",
        //            Title = "成功生成“" + channel.SubTitle + "”栏目详细页",
        //            UserId = admin.Id,
        //            UserName = admin.UserName
        //        });
        //        return 1;
        //    }
        //    AddSystemLog(new Model.SystemLog
        //    {
        //        AddTime = DateTime.Now,
        //        Content = "生成 “" + channel.SubTitle + "”栏目详细页失败",
        //        Title = "生成 “" + channel.SubTitle + "”栏目详细页失败",
        //        UserId = admin.Id,
        //        UserName = admin.UserName
        //    });
        //    return 0;
        //}

        /// <summary>
        /// 生成选中详细页
        /// </summary>
        /// <param name="classid"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        //[Mines.Ajax.AjaxMethod]
        //public virtual int CreateSelectHtml(int classid, List<int> ids, string ver)
        //{
        //    Model.Administrator admin;
        //    if (!Administrator.IsAdminLogin(out admin))
        //    {
        //        throw new AdministratorException("非法操作，未登录");
        //    }

        //    Smarta.Model.Channel channel = new BLL.Channel().GetModel(classid, ver);

        //    if (channel != null)
        //    {
        //        CreateHtmlPage.CreateHtmlDetailPage<T>(channel, ids, ver);
        //        AddSystemLog(new Model.SystemLog
        //        {
        //            AddTime = DateTime.Now,
        //            Content = "成功生成" + channel.SubTitle + "栏目选中详细页",
        //            Title = "成功生成" + channel.SubTitle + "栏目选中详细页成功",
        //            UserId = admin.Id,
        //            UserName = admin.UserName
        //        });
        //        return 1;
        //    }
        //    AddSystemLog(new Model.SystemLog
        //    {
        //        AddTime = DateTime.Now,
        //        Content = "生成 “" + channel.SubTitle + "”栏目选中详细页失败",
        //        Title = "生成 “" + channel.SubTitle + "”栏目选中详细页失败",
        //        UserId = admin.Id,
        //        UserName = admin.UserName
        //    });
        //    return 0;
        //}
        #endregion

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public virtual bool Exists(object Id)
        {
            return database.Exists<T>(Id);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="where"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public virtual bool Exists(string where, params object[] param)
        {
            return database.Exists<T>(where, param);
        }
        public int UpdateField(object PrimaryKey, string setsql, params object[] args)
        {
            return database.UpdateField<T>(PrimaryKey, setsql, args);
        }

        public int UpdateField(string wheresql, string setsql, params object[] args)
        {
            return database.UpdateField<T>(wheresql, setsql, args);
        }

        string getField(string field)
        {
            switch (field)
            {
                case "islock":
                    return "锁定";
                case "sortid":
                    return "排序";
                case "ishot":
                    return "热门";
                case "isred":
                    return "推荐";
                case "ismsg":
                    return "首页";
                case "istop":
                    return "置顶";
                default:
                    return field;
            }
        }

        [Mines.Ajax.AjaxMethod]
        public object updatesate(int id, string field, int value)
        {
            //Model.Administrator admin;
            //if (!Administrator.IsAdminLogin(out admin))
            //{
            //    throw new AdministratorException("非法操作，未登录");
            //}

            var classid = GetFieldValue<string>("classid", id);

            var channelTitle = new BLL.Channel().GetFieldValue<string>("SubTitle", classid);

            if (id > 0 && !string.IsNullOrEmpty(field))
            {
                field = field.ToLower();
                if (",islock,sortid,ishot,isred,isslide,ismsg,pro_adddel3,pro_adddel2,istop,".IndexOf("," + field.ToLower() + ",") > -1)
                {
                    int res = UpdateField(id, field + "=" + value);
                    return res;
                }

            }
            return null;
        }





        [Mines.Ajax.AjaxMethod]
        public object UpdateField(int id, string field, int value)
        {
            Model.Administrator admin;
            if (!Administrator.IsAdminLogin(out admin))
            {
                throw new AdministratorException("非法操作，未登录");
            }

            var classid = GetFieldValue<string>("classid", id);

            var channelTitle = new BLL.Channel().GetFieldValue<string>("SubTitle", classid);

            if (id > 0 && !string.IsNullOrEmpty(field))
            {
                field = field.ToLower();
                if (",islock,sortid,ishot,isred,isslide,ismsg,pro_adddel3,pro_adddel2,istop,".IndexOf("," + field.ToLower() + ",") > -1)
                {
                    int res = UpdateField(id, field + "=" + value);

                    AddSystemLog(new Model.SystemLog
                    {
                        AddTime = DateTime.Now,
                        Content = "修改" + getTypeCnName(typeof(T).Name) + "-" + channelTitle + " 属性“" + getField(field) + "”成功 类型   标题:" + GetFieldValue<string>("title", id),
                        //Title = "修改" + getTypeCnName(typeof(T).Name) + "-" + channelTitle + " 属性“" + getField(field) + "”成功 类型 标题:" + GetFieldValue<string>("title", id),
                        UserId = admin.Id,
                        UserName = admin.UserName
                    });

                    return res;
                }
                else
                {
                    throw new AdministratorException("非法操作，" + field + "未授权");
                }
            }
            AddSystemLog(new Model.SystemLog
            {
                AddTime = DateTime.Now,
                Content = "修改" + getTypeCnName(typeof(T).Name) + "属性“" + getField(field) + "”失败 类型  Title:" + GetFieldValue<string>("title", id),
                Title = "修改" + getTypeCnName(typeof(T).Name) + "属性“" + getField(field) + "”失败 类型 Title:" + GetFieldValue<string>("title", id),
                UserId = admin.Id,
                UserName = admin.UserName
            });
            return null;
        }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        [Mines.Ajax.AjaxMethod]
        public virtual int Add(T model)
        {
            var t = typeof(T);
            Model.Administrator admin = new Model.Administrator();
            if (t.Name != "SystemLog")
            {
                if (!Administrator.IsAdminLogin(out admin) && t.Name != "SYstemLog")
                {
                    throw new AdministratorException("非法操作，未登录");
                }
            }
            try
            {

                int res = int.Parse(database.Add(model).ToString());

                model = GetModel(res);

                var p = t.GetProperty("Url");

                if (p != null)
                {

                    var pv = p.GetValue<T>(model);

                    if (pv != null && !string.IsNullOrEmpty(pv.ToString()))
                        p.SetValue<T>(model, TemplateReplaceModel(pv.ToString(), "", model));

                }

                Update(model);

                if (t.Name.ToLower().IndexOf("del") < 0 && t.Name != "SystemLog" && t.Name != "MainChannel" && t.Name != "SubChannel")
                {
                    try
                    {
                        AddSystemLog(new Model.SystemLog
                        {
                            AddTime = DateTime.Now,
                            Content = "添加" + getTypeCnName(typeof(T).Name) + "内容成功  " + "  标题:" + t.GetProperty("Title").GetValue<T>(model),
                            Title = "添加" + getTypeCnName(typeof(T).Name) + "内容成功  " + " 标题:" + t.GetProperty("Title").GetValue<T>(model),
                            UserId = admin.Id,
                            UserName = admin.UserName
                        });
                    }
                    catch { }
                }
                return res;
            }

            catch
            {
                if (t.Name != "SystemLog" && t.Name != "SubChannel" && t.Name != "MainChannel")
                {
                    AddSystemLog(new Model.SystemLog
                    {
                        AddTime = DateTime.Now,
                        Content = "添加内容失败 类型 " + typeof(T).Name + " Title:" + t.GetProperty("Title").GetValue(model),
                        Title = "添加内容失败 类型 " + typeof(T).Name + " Title:" + t.GetProperty("Title").GetValue(model),
                        UserId = admin.Id,
                        UserName = admin.UserName
                    });
                }
                return 0;
            }
        }
        /// <summary>
        /// 前台用户增加一条数据
        /// </summary>
        [Mines.Ajax.AjaxMethod]
        public virtual int Add_V(T model)
        {
            var t = typeof(T);

            try
            {
                var p = t.GetProperty("Url");

                if (p != null)
                {
                    var pv = p.GetValue<T>(model);

                    if (pv != null && !string.IsNullOrEmpty(pv.ToString()))
                        p.SetValue<T>(model, TemplateReplaceModel(pv.ToString(), "", model));

                }

                int res = int.Parse(database.Add(model).ToString());

                return res;
            }

            catch
            {

                return 0;
            }
        }


        /// <summary>
        /// 更新一条数据
        /// </summary>
        [Mines.Ajax.AjaxMethod]
        public virtual object Update(T model)
        {
            Model.Administrator admin;
            if (!Administrator.IsAdminLogin(out admin))
            {
                throw new AdministratorException("非法操作，未登录");
            }
            var t = typeof(T);

            var p = t.GetProperty("Url");

            if (p != null)
            {
                var pv = p.GetValue(model);

                if (pv != null && !string.IsNullOrEmpty(pv.ToString()))

                    p.SetValue<T>(model, TemplateReplaceModel(pv.ToString(), "", model));

            }

            object res = database.Update(model);
            if (t.Name != "SystemLog" && t.Name != "MainChannel" && t.Name != "SubChannel" && t.Name != "Administrator")
            {
                try
                {
                    AddSystemLog(new Model.SystemLog
                    {
                        AddTime = DateTime.Now,
                        Content = "修改" + getTypeCnName(typeof(T).Name) + "内容 Title:" + t.GetProperty("Title").GetValue(model),
                        Title = "修改 " + getTypeCnName(typeof(T).Name) + "内容 Title:" + t.GetProperty("Title").GetValue(model),
                        UserId = admin.Id,
                        UserName = admin.UserName
                    });
                }
                catch { }
            }
            return res;
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        [Mines.Ajax.AjaxMethod]
        public virtual int Delete(int Id)
        {
            Model.Administrator admin;
            if (!Administrator.IsAdminLogin(out admin))
            {
                throw new AdministratorException("非法操作，未登录");
            }
            var res = database.Delete<T>(Id);

            AddSystemLog(new Model.SystemLog
            {
                AddTime = DateTime.Now,
                Content = "删除" + getTypeCnName(typeof(T).Name) + "内容 ：  Title:" + GetFieldValue<string>("title", Id),
                Title = "删除" + getTypeCnName(typeof(T).Name) + "内容 ：Title:" + GetFieldValue<string>("title", Id),
                UserId = admin.Id,
                UserName = admin.UserName
            });

            return res;
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public virtual T GetModel(int Id)
        {
            return database.GetModel<T>(Id);
        }

        public virtual T GetModel(int Id, string ver)
        {
            return database.GetModel<T>("where islock>-1 and id=@0 and ver=@1 ", Id, ver);
        }

        public virtual T GetModel(string where, params object[] param)
        {
            return database.GetModel<T>(where, param);
        }

        public virtual int Delete(string Where, params object[] param)
        {
            return database.Delete<T>(Where, param);
        }

        public virtual int Delete(int id, params object[] param)
        {
            return database.Delete<T>(" islock>-1 and id=" + id, param);
        }

        public virtual IEnumerable<T> Query(string Where, params object[] param)
        {
            return database.Query<T>(Where, param);
        }

        public virtual IEnumerable<T> Query(int top, string Where, params object[] param)
        {
            var pd = PetaPoco.Database.PocoData.ForType(typeof(T));

            return database.Query<T>(string.Format("select {2} * from {0} where {1} and islock>-1", database.EscapeTableName(pd.TableInfo.TableName), Where, top > 0 ? " top " + top : string.Empty), param);
        }

        public virtual IEnumerable<T> Query(int top, string Where, string Order, params object[] param)
        {
            var pd = PetaPoco.Database.PocoData.ForType(typeof(T));
            return database.Query<T>(string.Format("select {2} * from {0} where {1} and islock>-1 order by {3}",
                database.EscapeTableName(pd.TableInfo.TableName),
                Where,
                top > 0 ? " top " + top : string.Empty,
                Order), param);
        }

        public virtual PetaPoco.Page<T> Page(long pageSize, long currentPage, string strWhere, string filedOrder, params object[] param)
        {
            return database.Page<T>(pageSize, currentPage, strWhere, filedOrder, param);
        }

        [Mines.Ajax.AjaxMethod]
        public virtual int Deletes(List<int> ids)
        {
            Model.Administrator admin;
            if (!Administrator.IsAdminLogin(out admin))
            {
                throw new AdministratorException("非法操作，未登录");
            }
            string sql = " where (islock>-1 or islock is null) and id in(" + string.Join(",", ids) + ")";
            int res = Delete(sql);
            AddSystemLog(new Model.SystemLog
            {
                AddTime = DateTime.Now,
                Content = "批量删除" + getTypeCnName(typeof(T).Name) + "内容： ID:" + string.Join(",", ids),
                Title = "批量删除" + getTypeCnName(typeof(T).Name) + "内容： ID:" + string.Join(",", ids),
                UserId = admin.Id,
                UserName = admin.UserName
            });

            return res;

        }

        public virtual int Delete(int id, params object[] param)
        {
            return database.Delete<T>(" islock>-1 and id=" + id, param);
        }

        public virtual IEnumerable<T> Query(string Where, params object[] param)
        {
            return database.Query<T>(Where, param);
        }

        public virtual IEnumerable<T> Query(int top, string Where, params object[] param)
        {
            var pd = PetaPoco.Database.PocoData.ForType(typeof(T));

            return database.Query<T>(string.Format("select {2} * from {0} where {1} and islock>-1", database.EscapeTableName(pd.TableInfo.TableName), Where, top > 0 ? " top " + top : string.Empty), param);
        }

        public virtual IEnumerable<T> Query(int top, string Where, string Order, params object[] param)
        {
            var pd = PetaPoco.Database.PocoData.ForType(typeof(T));
            return database.Query<T>(string.Format("select {2} * from {0} where {1} and islock>-1 order by {3}",
                database.EscapeTableName(pd.TableInfo.TableName),
                Where,
                top > 0 ? " top " + top : string.Empty,
                Order), param);
        }

        public virtual PetaPoco.Page<T> Page(long pageSize, long currentPage, string strWhere, string filedOrder, params object[] param)
        {
            return database.Page<T>(pageSize, currentPage, strWhere, filedOrder, param);
        }

        /// <summary>
        /// 替换标签
        /// </summary>
        /// <param name="html"></param>
        /// <param name="pre"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual string TemplateReplaceModel(string html, string pre, object model)
        {
            return temp.TemplateReplaceModel(html, pre, model);
        }

        /// <summary>
        /// 替换标签
        /// </summary>
        /// <param name="html"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual string TemplateReplaceModel(string html, object model)
        {
            return temp.TemplateReplaceModel(html, string.Empty, model);
        }

        /// <summary>
        /// 替换标签
        /// </summary>
        /// <param name="html"></param>
        /// <param name="model"></param>
        /// <param name="htmlurl"></param>
        /// <returns></returns>
        public virtual string TemplateReplaceModel(string html, object model, out object htmlurl)
        {
            return temp.TemplateReplaceModel(html, string.Empty, model, out htmlurl);
        }

        /// <summary>
        /// 获取详细页末班
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual string GetDetailTemplatePath(object model)
        {
            return temp.GetDetailTemplatePath(model);
        }

        /// <summary>
        /// 获得主键值
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual object GetPrimaryKey(object model)
        {
            return temp.GetPrimaryKey(model);
        }

        /// <summary>
        /// 换取属性值
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <param name="field"></param>
        /// <param name="pri"></param>
        /// <returns></returns>
        public virtual T1 GetFieldValue<T1>(string field, object pri)
        {
            var pd = PetaPoco.Database.PocoData.ForType(typeof(T));
            return database.Query<T1>(string.Format("select {2} from {0} where {1}=@0 and islock>-1", database.EscapeTableName(pd.TableInfo.TableName), pd.TableInfo.PrimaryKey, field), pri).FirstOrDefault();
        }
        /// <summary>
        /// 换取属性值
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <param name="field"></param>
        /// <param name="where"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public virtual List<T1> GetFieldList<T1>(string field, string where, params object[] param)
        {
            var pd = PetaPoco.Database.PocoData.ForType(typeof(T));
            return database.Query<T1>(string.Format("select {2} from {0} where {1} and islock>-1 ", database.EscapeTableName(pd.TableInfo.TableName), where, field), param).ToList();
        }

        string getTypeCnName(string typeName)
        {
            switch (typeName)
            {
                case "SinglePage": return "单页面";
                case "Article": return "新闻";
                case "Administrator": return "管理员";
                case "Bannner": return "广告图";
                case "Channel": return "栏目";
                case "SubChannel": return "栏目";
                case "MainChannel": return "栏目";
                case "Downloads": return "下载页";
                case "Job": return "人才招聘";
                case "Product": return "产品";
                case "Role": return "用户组/角色";
                case "Video": return "视频";
                case "Version": return "站点管理";
                default: return typeName;
            }
        }



        //===================== start 项目新增方法 ========================================================

        /// <summary>
        /// 删除列表多条数据（wei 添加 2015.9.30）
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Mines.Ajax.AjaxMethod]
        public virtual int Deletes_M(List<int> ids)
        {
            string sql = " where (islock>-1 or islock is null) and id in(" + string.Join(",", ids) + ")";
            int res = Delete(sql);

            return res;

        }


        /// <summary>
        /// 商户会员上传--不用验证权限（2015.9.30 wei 添加）
        /// </summary>
        /// <param name="id"></param>
        /// <param name="field"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        [Mines.Ajax.AjaxMethod]
        public object UpdateField_M(int id, string field, int value)
        {
            if (id > 0 && !string.IsNullOrEmpty(field))
            {
                field = field.ToLower();
                if (",islock,sortid,ishot,isred,isslide,ismsg,pro_adddel3,pro_adddel2,istop,".IndexOf("," + field.ToLower() + ",") > -1)
                {
                    int res = UpdateField(id, field + "=" + value);

                    return res;
                }
                else
                {
                    throw new AdministratorException("非法操作，" + field + "未授权");
                }
            }

            return null;
        }

        /// <summary>
        /// 增加一条数据(2015.9.15 注册添加)
        /// </summary>
        [Mines.Ajax.AjaxMethod]
        public virtual int Add2(T model)
        {
            try
            {
                int res = int.Parse(database.Add(model).ToString());
                return res;
            }
            catch
            {
                return 0;
            }
        }


        /// <summary>
        /// 更新一条数据(2015.9.17)
        /// </summary>
        [Mines.Ajax.AjaxMethod]
        public virtual object Update2(T model)
        {
            return database.Update(model);
        }




        //===================== end 项目新增方法 ========================================================

#endif
    }
}
